package cn.yechen.yygh.cmn.service.impl;

import cn.yechen.yygh.cmn.listener.DictListener;
import cn.yechen.yygh.cmn.mapper.DictMapper;
import cn.yechen.yygh.cmn.service.DictService;
import cn.yechen.yygh.model.cmn.Dict;
import cn.yechen.yygh.vo.cmn.DictEeVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yechen
 * @create 2021-08-16 10:31
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        List<Dict> dictList = baseMapper.selectList(queryWrapper);
        // 编历 list 集合，为每个 dict 对象设置 hasChildren 属性
        for (Dict dict : dictList) {
            dict.setHasChildren(hasChild(dict.getId()));
        }
        return dictList;
    }

    // 判断 id 下面是否有子节点
    private boolean hasChild(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        // 有子节点 count>0，返回 true，没有子节点 count=0，返回 false
        return count > 0;
    }

    @Override
    public void exportDictData(HttpServletResponse response) {
        // 设置响应信息
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        // 文件名
        String fileName = "数据字典" + System.currentTimeMillis();
        // 这里 URLEncoder.encode 可以防止中文乱码
        try {
            fileName = URLEncoder.encode(fileName,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 设置响应头
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 查询数据字典
        List<Dict> dictList = baseMapper.selectList(null);
        // 将 Dict 转换成 DictEeVo 对象
        List<DictEeVo> dictEeVoList = new ArrayList<>(dictList.size());
        for (Dict dict : dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            // 对象转换
            BeanUtils.copyProperties(dict, dictEeVo, DictEeVo.class);
            dictEeVoList.add(dictEeVo);
        }

        // 通过流导出 excel
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    @CacheEvict(value = "dict", allEntries = true)
    public void importDictData(MultipartFile file) {
        // 上传
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getDictName(String dictcode, String value) {
        // 查询条件
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        // value 是统一的查询条件
        queryWrapper.eq("value", value);

        // 是否存在查询条件 dictcode
        if (!StringUtils.isEmpty(dictcode)) {
            // 需要 dictcode 作为查询条件
            // 通过 dictcode 查询出符合的父字典
            Dict parentDict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictcode));
            // 将父字典的 id 作为查询条件
            queryWrapper.eq("parent_id", parentDict.getId());
        }

        // 执行查询
        Dict dict = baseMapper.selectOne(queryWrapper);
        return dict.getName();
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict parentDict = this.getDictByDictCode(dictCode);
        if(null == parentDict) return null;
        return this.findChildData(parentDict.getId());
    }

    @Override
    public List<Dict> findByParentId(Long parentId) {
        List<Dict> childData = this.findChildData(parentId);
        return childData;
    }

    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code", dictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);
        return dict;
    }
}
